/* CalSyncUm 
 * Copyright (c) 2006,2007 Arthur van Bunningen
 * Based on L-dopa Calendar Sync, Copyright (c) 2006 Richard Stoner
 * 
 * This program is in no way affiliated with Google, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/


using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace calsyncum
{
    
    /// <summary>
    /// A collection of utilities written to interface with the synclist
    /// </summary>
    class SyncList
    {
        XmlDocument internList;
        GoAmi mainForm;
        String filename;

        public SyncList(GoAmi mainForm, String filename)
        {
            this.mainForm = mainForm;
            this.filename = filename;
            internList = new XmlDocument();
            try
            {
                internList.Load(filename);
            }
            catch (System.IO.FileNotFoundException)
            {
                //if file is not found, create a new xml file
                XmlTextWriter tempWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
                tempWriter.Formatting = Formatting.Indented;
                tempWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                tempWriter.WriteStartElement("SyncList");
                tempWriter.WriteAttributeString("modified", XmlConvert.ToString(DateTime.Now.ToUniversalTime()));
                tempWriter.WriteAttributeString("gusername", "@");
                tempWriter.WriteAttributeString("gpassword", "@");
                tempWriter.Close();
                internList.Load(filename);
            }

        }

           
        public void save()
        {
            internList["SyncList"].SetAttribute("modified", XmlConvert.ToString(DateTime.Now.ToUniversalTime()));
            internList.Save(filename);
        }

        public DateTime getLastModifiedDate()
        {
            DateTime modDate = DateTime.MinValue;
            if (internList["SyncList"].GetAttribute("modified") != null)
            {
                try
                {
                    modDate = XmlConvert.ToDateTime(internList["SyncList"].GetAttribute("modified"));
                }
                catch (System.FormatException)
                {
                    return modDate;
                }
            }
            return modDate;
        }

        public String getGUsername()
        {
            String retString = null;
            if (internList["SyncList"].GetAttribute("gusername") != null)
            {
                retString = internList["SyncList"].GetAttribute("gusername");
                if (retString.Length < 3)
                {
                    // account names shorter than 3 characters not allowed
                    return null;
                }
            }
            return retString;
        }

        public String getGPassword()
        {
            String retString = null;
            if (internList["SyncList"].GetAttribute("gpassword") != null)
            {
                retString = internList["SyncList"].GetAttribute("gpassword");
                if (retString.Length < 3)
                {
                    // passwords than 3 characters not allowed
                    return null;
                }
            }
            return retString;
        }



        public void storeLogin(string gusername, string gpassword)
        {
            internList["SyncList"].SetAttribute("gusername", gusername);
            internList["SyncList"].SetAttribute("gpassword", gpassword);
        }


        public XmlNode findbyGid(string googleid)
        {
            XmlNodeList foundGID = internList.SelectNodes("*/EventNode[@Gid='" + googleid + "']");

            if (foundGID.Count == 0 )
            {
                //found more than one or none
               // Console.WriteLine("returned no findbyGID");
                return null;
            }
            else
            {
                return foundGID[0];
            }
        }

        public XmlNode findbyOid(string outlookid)
        {
            XmlNodeList foundOID = internList.SelectNodes("*/EventNode[@Oid='" + outlookid + "']");

            if (foundOID.Count != 1)
            {
                //found more than one or none
                return null;
            }
            else
            {
                return foundOID[0];
            }
        }

        public void updateGidfromOid(string outlookid, string googleid)
        {
            deletebyOid(outlookid);
            addBoth(googleid, outlookid);            
        }

        public void updateOidfromGid(string googleid, string outlookid)
        {
            deletebyGid(googleid);
            addBoth(googleid, outlookid);
        }

        public void deletebyOid(string outlookid)
        {
            findbyOid(outlookid).ParentNode.RemoveChild(findbyOid(outlookid));
            Console.WriteLine("Removed Oid:" + outlookid);            
        }

        public void deletebyGid(string googleid)
        {
            findbyGid(googleid).ParentNode.RemoveChild(findbyGid(googleid));
            Console.WriteLine("Removed Gid:" + googleid);
        }

        public void addFromGid(string googleid)
        {
            XmlNode root = internList.DocumentElement;
            XmlElement eventNode = internList.CreateElement("EventNode");
            root.AppendChild(eventNode);
            eventNode.SetAttribute("Oid", "");
            eventNode.SetAttribute("Gid", googleid);
        }

        public void addFromOid(string outlookid)
        {
            XmlNode root = internList.DocumentElement;
            XmlElement eventNode = internList.CreateElement("EventNode");
            root.AppendChild(eventNode);
            eventNode.SetAttribute("Oid", outlookid);
            eventNode.SetAttribute("Gid", "");
        }

        public void addBoth(string googleid, string outlookid)
        {
            XmlNode root = internList.DocumentElement;
            XmlElement eventNode = internList.CreateElement("EventNode");
            root.AppendChild(eventNode);
            eventNode.SetAttribute("Oid", outlookid);
            eventNode.SetAttribute("Gid", googleid);
        }

        public XmlNode findbyboth(string googleid, string outlookid)
        {
            XmlNodeList foundboth = internList.SelectNodes("*/EventNode[@Oid='" + outlookid + "'][@Gid='" + googleid + "']");

            if (foundboth.Count != 1)
            {
                //found more than one or none
                return null;
            }
            else
            {
                return foundboth[0];
            }
        }

        public String getGoogleidForOid(string outlookid)
            {
                XmlNode tempnode = findbyOid(outlookid);
                if (tempnode != null)
                {
                    return tempnode.Attributes[1].Value;
                }
                return null;
            }

        public String getOutlookidForGid(string googleid)
            {
                XmlNode tempnode = findbyGid(googleid);
                if (tempnode != null)
                {
                    return tempnode.Attributes[0].Value;
                }
                return null;
            }

    }
}
